import { useUserStore } from '@/store';
import { getToken } from '@/utils/auth';
import { Message, Modal } from '@arco-design/web-vue';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import axios from 'axios';

export interface HttpResponse<T = unknown> {
  status: number;
  msg: string;
  code: number;
  data: T;
}

if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // let each request carry token
    // this example using the JWT token
    // Authorization is a custom headers key
    // please modify it according to the actual situation
    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      // config.headers.Authorization = `Bearer ${token}`;
      const userStore = useUserStore();
      console.log(config);
      if (config?.noPublic) return config;
      config.headers.token = `${token}`;
      config.headers.id = `${userStore.id}`;
      if (config.method == 'get') {
        config.params = {
          user_id: userStore.id,
          role: userStore.role,
          squad_id_: userStore.squad_id,
          ...config.params,
        };
      } else {
        config.data = {
          user_id: userStore.id,
          role: userStore.role,
          squad_id_: userStore.squad_id,
          ...config.data,
        };
      }

      //
    }
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);
// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.
    const sucessCode = [1, 20000];
    if (!sucessCode.includes(res.code)) {
      Message.error({
        content: res.msg || 'Error',
        duration: 5 * 1000,
      });
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if ([3].includes(res.code)) {
        Modal.error({
          title: res.msg,
          maskClosable: false,
          content:{
            下线通知: `您的账号已在另一台终端登录`,
            登录身份失效: `您的登录已失效，请重新登录`,
          }[res.msg] as string,
          okText: '重新登录',
          async onOk() {
            const userStore = useUserStore();

            await userStore.logout();
            window.location.reload();
          },
        });
      }
      return Promise.reject(new Error(res.msg || 'Error'));
    }
    return res;
  },
  (error) => {
    Message.error({
      content: error.msg || 'Request Error',
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);
